#define _GNU_SOURCE
#include <mqueue.h>
#include <pthread.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>

static char *mqueue_name = "/mqueue_test";
static mqd_t mqueue_mark;

void *frist_thread_func(void *args)
{
    printf("This is the first thread,id:%d\n", gettid());
    char msg[256] = {0};
    ssize_t size = mq_receive(mqueue_mark, msg, 256, 0);
    if (size > 0)
    {
        printf("接收消息成功，消息为:%s\n", msg);
    }
    else
    {
        printf("接受消息失败\n");
    }
    return NULL;
}

void *second_thread_func(void *args)
{
    printf("This is the second thread,id:%d\n", gettid());
    char *msg = "Hello,world!";
    mq_send(mqueue_mark, msg, strlen(msg) + 1, 0);
    return NULL;
}

int main(void)
{
    struct mq_attr attr = {
        .mq_maxmsg = 10,
        .mq_msgsize = 256};
    // 创建一个消息队列，当前用户可读写，权限为0644
    mqueue_mark = mq_open(mqueue_name, O_CREAT | O_RDWR, 0644, &attr);

    pthread_t pth1, pth2;
    pthread_create(&pth1, NULL, frist_thread_func, NULL);
    pthread_create(&pth2, NULL, second_thread_func, NULL);

    pthread_join(pth1, NULL);
    pthread_join(pth2, NULL);
    // 关闭消息队列
    mq_close(mqueue_mark);
    // 删除消息队列
    mq_unlink(mqueue_name);
    return 0;
}